<?php
/**
 * Created by PhpStorm.
 * User: junyv
 * Date: 2016/9/18
 * Time: 11:52
 */

namespace app\manage\controller;
class AskCate extends Base
{
//前置操作定义
    protected $beforeActionList = [
        // 'second' =>  ['except'=>'hello'],
        'beforeEdit'  =>  ['only'=>'edit,add'],
    ];
    private $mod;
    public function _initialize(){
        parent::_initialize();
        $this->mod = model('ask_cate');
    }
    public function index() {
        $sort  = input("param.sort", 'ordid');
        $order = input("param.order",'ASC');
        $tree = new \org\Tree();
        $tree->icon = ['│ ','├─ ','└─ '];
        $tree->nbsp = '&nbsp;&nbsp;&nbsp;';
        $result = $this->mod->order($sort . ' ' . $order)->select();
        $result = objToArray($result);
        $array = [];
        foreach($result as $r) {
            $r['str_status'] = '<img data-tdtype="toggle" data-id="'.$r['id'].'" data-field="status" data-value="'.$r['status'].'" src="/static/manage/images/toggle_' . ($r['status'] == 0 ? 'disabled' : 'enabled') . '.gif" />';
            $r['str_hot'] = '<img data-tdtype="toggle" data-id="'.$r['id'].'" data-field="hot" data-value="'.$r['hot'].'" src="/static/manage/images/toggle_' . ($r['hot'] == 0 ? 'disabled' : 'enabled') . '.gif" />';
            $r['str_manage'] = '<a href="javascript:;" class="J_showdialog" data-uri="'.url('AskCate/add',['pid'=>$r['id']]).'" data-title="添加子栏目" data-id="add" data-width="500" data-height="360">添加子栏目</a> |
                                <a href="javascript:;" class="J_showdialog" data-uri="'.url('AskCate/edit',['id'=>$r['id']]).'" data-title="编辑-'. $r['name'] .'" data-id="edit" data-width="500" data-height="360">编辑</a> |
                                <a href="javascript:;" class="J_confirmurl" data-acttype="ajax" data-uri="'.url('AskCate/delete',['id'=>$r['id']]).'" data-msg="'.sprintf('确定要删除么？',$r['name']).'">删除</a>';
            $r['parentid_node'] = ($r['pid'])? ' class="child-of-node-'.$r['pid'].'"' : '';
            $array[] = $r;
        }
        $str  = "<tr id='node-\$id' \$parentid_node>

                <td align='center'>\$id</td>
                <td>\$spacer<span data-tdtype='edit' data-field='name' data-id='\$id' class='tdedit'>\$name</span></td>
				<td align='center'>\$alias</td>
                <td align='center'><span data-tdtype='edit' data-field='ordid' data-id='\$id' class='tdedit'>\$ordid</span></td>

                <td align='center'>\$str_status</td>
                <td align='center'>\$str_hot</td>
                <td align='center'>\$str_manage</td>
                </tr>";
        $tree->init($array);
        $list = $tree->get_tree(0, $str);
        $this->assign('list', $list);
        //bigmenu (标题，地址，弹窗ID，宽，高)
        $big_menu = [
            'title' => '添加栏目',
            'iframe' => url('AskCate/add'),
            'id' => 'add',
            'width' => '500',
            'height' => '360'
        ];
        $this->assign('big_menu', $big_menu);
        $this->assign('list_table', true);
       return $this->fetch();
    }
    protected function beforeEdit(){
        $pid = input('param.pid/d');
        $spid = 0;
        if ($pid) {
            $spid = $this->mod->where(['id'=>$pid])->value('spid');
            $spid = $spid ? $spid.$pid : $pid;
        }
        $this->assign('spid', $spid);
    }
    public function addDo(){
        //注册前置事件 只对模型调用
        \app\common\model\AskCate::event('before_insert',function($obj){
            $aliasRadio = input('param.aliasRadio/d');
            //检测分类是否存在
            if($this->mod->name_exists($obj->name, $obj->pid,0)){
                $this->ajaxReturn(0, '分类名称已存在');
            }
            //生成spid
            $obj->spid = $this->mod->get_spid($obj->pid);
            //栏目别名
            if($obj->alias==''){
                $py = new \org\Pinyin();
                if($aliasRadio==1){
                    $obj->alias=trim($py->getFirstPY($obj->name));	//首字母拼音
                }else{
                    $obj->alias=trim($py->getAllPY($obj->name));		//全部拼音
                }
            }
            if ($this->mod->name_exists($obj->alias, 0, 0)) {
                $this->ajaxReturn(0, '分类名称已存在');
            }
            return true;
        });
        parent::addDo();
    }
    public function delete(){
        //判断是否有下级栏目或文章存在  存在则不能删除
        \app\common\model\AskCate::event('before_delete',function($obj){
            $id = $obj->id;
            //是否有下级栏目
            $child = $this->mod->get_child_ids($id);
            //是否有文章
            $info = model('article')->where(['cate_id'=>$id])->value('id');
            if(!empty($child) || !empty($info)){
                return false;
            }
            return true;
        });
        parent::delete();
    }
    public function ajaxGetchilds() {
        $id = input('param.id/d');
        $return = $this->mod->field('id,name')->where(['pid'=>$id])->select();
        if ($return) {
            $this->ajaxReturn(1, 'success', $return);
        } else {
            $this->ajaxReturn(0, 'error');
        }
    }

    /**
     * 更新文章分类缓存
     */
    public function cache(){
        if($this->doCache()){
            $this->success('问答分类缓存更新成功');
        }else{
            $this->error('问答分类缓存更新失败');
        }
    }
    public function doCache(){
        $lists = $this->mod->field('id,pid,name,hot,alias')->where('status',1)->select();
        if($lists){
            $cate = objToArray($lists);//普通列表
            $temp = [];
            foreach($cate as $v){
                $temp[$v['id']] = $v;
            }
            $tree = list_to_tree($temp);//树形列表
            cache('askCate',['cate'=>$temp,'tree'=>$tree]);
            return true;
        }
        return false;

    }
}